<template>
  <div>
    <a-upload list-type="picture-card" :file-list="fileList" :before-upload="beforeUpload" :transform-file="transformFile" @preview="handlePreview" @change="handleChange">
      <div v-if="fileList.length < 1">
        <a-icon type="plus" />
        <div class="ant-upload-text">立即上传</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
import { getBase64 } from "@/utils/convertUtils/convert";
export default {
  props: {
    fileList: {
      type: Array,
      require: false,
      default: () => []
    },
  },

  data() {
    return {
      previewVisible: false,
      previewImage: "",
      internalFileList: [] // 新增内部文件列表
    };
  },
  watch: {
    fileList: {
      immediate: true,
      handler(newVal) {
        // 转换传入的fileList为a-upload需要的格式
        if (newVal && newVal.length > 0) {
          this.internalFileList = this.normalizeFileList(newVal);
        } else {
          this.internalFileList = [];
        }
      }
    }
  },
  methods: {
    // 标准化文件列表格式
    normalizeFileList(files) {
      return files.map(file => {
        if (file instanceof File || file instanceof Blob) {
          return {
            uid: `file-${Date.now()}-${Math.random().toString(16).slice(2)}`,
            name: file.name,
            status: 'done',
            url: URL.createObjectURL(file),
            thumbUrl: URL.createObjectURL(file),
            originFileObj: file
          };
        }
        return file; // 已经是标准格式的直接返回
      });
    },
    //#region 上传图片
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange(info) {
      // 上传数据改变时
      //   if (info.file.status === "done") {
      //     const res = info.file.response;
      //     if (res.code === 0) {
      //       this.$message.error(`图片上传成功`);
      //     } else {
      //       this.$message.error(`图片上传失败`);
      //     }
      //   } else if (info.file.status === "error") {
      //     this.$message.error(`图片上传失败`);
      //   }
      let fileList = [...info.fileList];

      // 转换文件格式
      fileList = fileList.map(file => {
        if (file.response) {
          return {
            ...file,
            url: file.response.url,
            status: 'done'
          };
        }
        return file;
      }).slice(-1); // 只保留最新一个文件

      // 提取原始文件对象传递给父组件
      const rawFiles = fileList.map(file => file.originFileObj || file);
      this.$emit("uploadCallBack", rawFiles);

      // 更新内部文件列表（标准化格式）
      this.internalFileList = this.normalizeFileList(rawFiles);
    },
    // 上传前对文件限制
    beforeUpload(file) {
      const format =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/bmp";
      if (!format) {
        this.$message.error("仅支持 JPG/JPEG/PNG/BMP 格式!");
        return;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小不能超过2MB!");
        return;
      }
      if (isLt2M && format) {
        // 立即返回文件对象给父组件
        this.$emit("uploadCallBack", [file]);
      }
      return false;
    },
    // 上传后添加水印
    transformFile(file) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          const canvas = document.createElement("canvas");
          const img = document.createElement("img");
          img.src = reader.result;
          img.onload = () => {
            const ctx = canvas.getContext("2d");
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
            ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
            ctx.font = "20px Arial";
            ctx.textAlign = "center";
            ctx.fillText("Watermark", canvas.width / 2, canvas.height / 2);
            canvas.toBlob(resolve, file.type);
          };
        };
      });
    },
    //#endregion

    beforeDestroy() {
      // 清理ObjectURL防止内存泄漏
      this.internalFileList.forEach(file => {
        if (file.url && file.url.startsWith('blob:')) {
          URL.revokeObjectURL(file.url);
        }
        if (file.thumbUrl && file.thumbUrl.startsWith('blob:')) {
          URL.revokeObjectURL(file.thumbUrl);
        }
      });
    }
  },
};
</script>
<style scoped>
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.avatar {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>

// 父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted。